/**
 * 从页面中获取下载链接
 */
import htt from "../htt"

let headers:any = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.44"
}

export default function getDown (url:any){
    return new Promise(resol=>{
        htt(url).get(url,{headers},(res:any)=>{

            let html = "";
            switch (res.statusCode){
                case 404:{
                    resol([]);
                    break;
                }
                case 301:{
                    getDown(res.headers.location).then(e=>resol(e));
                    break;
                }
                case 200:{
                    res.on("data",(num:any)=>html+=num)
                    res.on("end",()=>{
                        // 获取到完整的html了
                        html = html.match(/普通下载地址[^]*?<\/div>/g)?html.match(/普通下载地址[^]*?<\/div>/g)[0]:null;
                        // 解析出来链接以及名称
                        let dow = html.match(/<a[^]*?<\/a>/g).map(e=>{
                            return {
                                url :e.match(/href=".*?"/)?e.match(/href=".*?"/)[0].replace(/href="|"|amp;/g,""):null,
                                name:e.match(/>.*?<\/a>/)?e.match(/>.*?<\/a>/)[0].replace(/>|<\/a>/g,"") : null
                            }          
                        }).filter(e=>e.url) || []
                        resol(dow)
                    })
                    break;
                } 
                default :{
                    console.log(res.statusCode)
                }
            }
            
        })
    })
    
}

